package com.example.lprxjava;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Author by lp,on 2021/7/20/020,14:27.
 * Rxjava 功能操作符
 */
public class FunctionFragement extends BaseFragment {

    private static final String TAG = "FunctionFragement";

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        getLifecycle().addObserver(new RxLifecycle());
    }

    @Override
    String getTAG() {
        return TAG;
    }

    @Override
    String getTitle() {
        return "RxJava 功能操作符";
    }

    @Override
    int getFragmentLayoutId() {
        return R.layout.function_frqagment;
    }

    @Override
    void onLoad(View view) {
        create();

    }

    //subscribeOn 决定事件所处的线程，全局只能由最上游的subscribeOn决定
    //observeOn 决定下游观察者回调的线程
    private void create() {
        observable = Observable.create(new ObservableOnSubscribe<Object>() {
            @Override
            public void subscribe(ObservableEmitter<Object> e) throws Exception {
                Log.i(TAG, "subscribe Thread: " + Thread.currentThread().getName());
                e.onNext("create方式创建...");
                e.onComplete();
            }
        })
//                .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                //复用了被观察者
                .compose(RxLifecycle.bindRxLifecycle(this))
                .compose(new SchedulerTransformer<>());

        observable.subscribe(observer);
        observable.observeOn(Schedulers.io()).subscribe(observer);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.i(TAG, "onDestroyView: ");

    }
}
